package com.flycms.modules.system.controller;

import java.util.List;

import com.flycms.common.constant.UserConstants;
import com.flycms.common.utils.SecurityUtils;
import com.flycms.common.utils.ServletUtils;
import com.flycms.common.utils.StrUtils;
import com.flycms.common.utils.page.Pager;
import com.flycms.common.utils.poi.ExcelUtil;
import com.flycms.common.validator.Order;
import com.flycms.common.validator.Sort;
import com.flycms.framework.aspectj.lang.annotation.Log;
import com.flycms.framework.aspectj.lang.enums.BusinessType;
import com.flycms.framework.security.LoginAdmin;
import com.flycms.framework.security.service.TokenService;
import com.flycms.framework.web.controller.BaseController;
import com.flycms.framework.web.domain.AjaxResult;
import com.flycms.framework.web.page.TableDataInfo;
import com.flycms.modules.system.domain.FlyAdmin;
import com.flycms.modules.system.service.IFlyAdminService;
import com.flycms.modules.system.service.IFlyPostService;
import com.flycms.modules.system.service.IFlyRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户信息
 * 
 * @author kaifei sun
 */
@RestController
@RequestMapping("/system/admin")
public class FlyAdminController extends BaseController
{
    @Autowired
    private IFlyAdminService adminService;

    @Autowired
    private IFlyRoleService roleService;

    @Autowired
    private IFlyPostService postService;

    @Autowired
    private TokenService tokenService;
    /////////////////////////////////
    ///////       增加       ////////
    /////////////////////////////////
    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:admin:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody FlyAdmin user)
    {
        if (UserConstants.NOT_UNIQUE.equals(adminService.checkAdminNameUnique(user.getAdminName())))
        {
            return AjaxResult.error("新增用户'" + user.getAdminName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(adminService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getAdminName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(adminService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getAdminName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(adminService.insertAdmin(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:admin:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody FlyAdmin admin)
    {
        adminService.checkAdminAllowed(admin);
        admin.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(adminService.updateAdminStatus(admin));
    }
    /////////////////////////////////
    ///////        刪除      ////////
    /////////////////////////////////
    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:admin:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(adminService.deleteAdminByIds(userIds));
    }



    /////////////////////////////////
    ///////        修改      ////////
    /////////////////////////////////
    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:admin:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody FlyAdmin user)
    {
        adminService.checkAdminAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(adminService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getAdminName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(adminService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getAdminName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(adminService.updateAdmin(user));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:admin:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody FlyAdmin admin)
    {
        adminService.checkAdminAllowed(admin);
        admin.setPassword(SecurityUtils.encryptPassword(admin.getPassword()));
        admin.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(adminService.resetPwd(admin));
    }

    /////////////////////////////////
    ///////        查詢      ////////
    /////////////////////////////////

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:admin:list')")
    @GetMapping("/list")
    public TableDataInfo list(FlyAdmin user,
                              @RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @Sort @RequestParam(defaultValue = "create_time") String sort,
                              @Order @RequestParam(defaultValue = "desc") String order)
    {
        Pager<FlyAdmin> pager = adminService.selectAdminPager(user, pageNum, pageSize, sort, order);
        return getDataTable(pager.getList(),pager.getTotal());
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:admin:export')")
    @GetMapping("/export")
    public AjaxResult export(FlyAdmin admin,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @Sort @RequestParam(defaultValue = "create_time") String sort,
                             @Order @RequestParam(defaultValue = "desc") String order)
    {
        Pager<FlyAdmin> pager = adminService.selectAdminPager(admin, pageNum, pageSize, sort, order);
        ExcelUtil<FlyAdmin> util = new ExcelUtil<FlyAdmin>(FlyAdmin.class);
        return util.exportExcel(pager.getList(), "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:admin:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<FlyAdmin> util = new ExcelUtil<FlyAdmin>(FlyAdmin.class);
        List<FlyAdmin> adminList = util.importExcel(file.getInputStream());
        LoginAdmin loginAdmin = tokenService.getLoginAdmin(ServletUtils.getRequest());
        String operName = loginAdmin.getUsername();
        String message = adminService.importAdmin(adminList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<FlyAdmin> util = new ExcelUtil<FlyAdmin>(FlyAdmin.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:admin:query')")
    @GetMapping(value = { "/", "/{adminId}" })
    public AjaxResult getInfo(@PathVariable(value = "adminId", required = false) Long adminId)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("roles", roleService.selectRoleAll());
        ajax.put("posts", postService.selectPostAll());
        if (StrUtils.isNotNull(adminId))
        {
            ajax.put(AjaxResult.DATA_TAG, adminService.findAdminById(adminId));
            ajax.put("postIds", postService.selectPostListByAdminId(adminId));
            ajax.put("roleIds", roleService.selectRoleListByAdminId(adminId));
        }
        return ajax;
    }

}